package com.itheima.appserver.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.Method;
import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.appserver.config.HuanXinConfig;
import com.itheima.appserver.exception.MyException;
import com.itheima.appserver.exception.ResultError;
import com.itheima.appserver.interceptor.UserThreadLocal;
import com.itheima.appserver.service.IMService;
import com.itheima.appserver.service.MyCenterService;
import com.itheima.commons.pojo.Announcement;
import com.itheima.commons.pojo.Comment;
import com.itheima.commons.pojo.UserInfo;
import com.itheima.commons.pojo.Users;
import com.itheima.commons.vo.*;
import com.itheima.interfaces.AnnouncementApi;
import com.itheima.interfaces.CommentApi;
import com.itheima.interfaces.UserInfoApi;
import com.itheima.interfaces.UsersApi;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class IMServiceImpl implements IMService {

    @Autowired
    private MyCenterService myCenterService;

    @Reference
    private UsersApi usersAPI;

    @Autowired
    private RequestService requestService;

    @Autowired
    private HuanXinConfig huanXinConfig;

   @Reference
   private UserInfoApi userInfoAPI;

   @Reference
   private CommentApi commentAPI;

   @Reference
   private AnnouncementApi announcementAPI;
    @Override
    public UserInfoVo selectUserInfo(String huanxinId) {
       return myCenterService.queryUserInfoByUserId(Convert.toLong(StrUtil.subAfter(huanxinId,"_",true)));
    }

    @Override
    public void contacts(Integer userId) {
        Users users = new Users();
        users.setId(new ObjectId());
        users.setUserId(UserThreadLocal.getUserId());
        users.setFriendId(userId.longValue());
        users.setDate(System.currentTimeMillis());
        usersAPI.saveUsers(users);

        Users users2 = new Users();
        users.setId(new ObjectId());
        users.setUserId(userId.longValue());
        users.setFriendId(UserThreadLocal.getUserId());
        users.setDate(System.currentTimeMillis());
        usersAPI.saveUsers(users2);

        //环信中添加好友
        HttpResponse response = requestService.execute(huanXinConfig.getUrl() + huanXinConfig.getOrgName() + "/" + huanXinConfig.getAppName() + "/users/HX_" + UserThreadLocal.getUserId() + "/contacts/users/" + userId, null, Method.POST);
        if (!response.isOk()) {
            throw new MyException(ResultError.sendHuanXinMsgError());
        }
    }

    @Override
    public PageResult selectLinkman(Integer page, Integer pagesize, String keyword) {
        //根据自己的id 查找好友
        List<Users> usersList = usersAPI.selectFriendByUserId(page, pagesize, keyword, UserThreadLocal.getUserId());
        //查询好友信息
        List<Long> friendId = CollUtil.getFieldValues(usersList, "friendId", Long.class);
        Map<Long, UserInfo> userInfoMap = userInfoAPI.findUserInfoListByUserIdsBykeyword(friendId, keyword);
        List<UsersVo> list = new ArrayList<>();

        for (UserInfo userInfo : userInfoMap.values()) {

            UsersVo usersVo = new UsersVo();
            usersVo.setId(userInfo.getUserId());
            usersVo.setUserId("HX_" + userInfo.getUserId());
            usersVo.setAvatar(userInfo.getLogo());
            usersVo.setNickname(userInfo.getNickName());
            usersVo.setGender(userInfo.getSex() == 1 ? "man" : "woman");
            usersVo.setAge(userInfo.getAge());
            usersVo.setCity(userInfo.getCity());
            list.add(usersVo);
        }
        return new PageResult(page,pagesize,0L,list);
    }

    @Override
    public PageResult selectListCount(Integer page, Integer pagesize, Long userId, int i) {
        //从评论表中通过自己的id 找到评估过我的id
        List<Comment> commentList = commentAPI.selectByPublishUserId(page, pagesize, userId, i);
        List<Long> userIds = CollUtil.getFieldValues(commentList, "userId", Long.class);
        Map<Long, UserInfo> publishInfo = userInfoAPI.findPublishInfo(userIds);
        List<MessageCommentVo> messageCommentVos = new ArrayList<>();
        for (Comment comment : commentList) {
            MessageCommentVo messageCommentVo = new MessageCommentVo();
            UserInfo userInfo = publishInfo.get(comment.getUserId());
            messageCommentVo.setId(userInfo.getUserId().toString());
            messageCommentVo.setAvatar(userInfo.getLogo());
            messageCommentVo.setNickname(userInfo.getNickName());
            messageCommentVo.setCreateDate(DateUtil.format(new DateTime(comment.getCreated()), "yyyy-MM-dd HH:mm"));
            messageCommentVos.add(messageCommentVo);
        }
        return new PageResult(page,pagesize,0L,messageCommentVos);
    }

    @Override
    public PageResult selectAnnouncements(Integer page, Integer pagesize) {
        List<Announcement> announcement = announcementAPI.selectAnnouncement();
        List<AnnouncementVo> announcementVos = new ArrayList<>();
        for (Announcement announcement1 : announcement) {
            AnnouncementVo announcementVo = new AnnouncementVo();
            announcementVo.setId(announcement1.getId().toString());
            announcementVo.setTitle(announcement1.getTitle());
            announcementVo.setDescription(announcement1.getDescription());
            announcementVo.setCreateDate(DateUtil.format(announcement1.getCreated(),"yyyy-MM-dd HH:ss"));
            announcementVos.add(announcementVo);
        }
        return new PageResult(page,pagesize,0L,announcementVos);
    }
}
